<template>
  <div>
    <el-card>
      <el-form
        ref="editFormRef"
        :model="editedBlog"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item label="文章ID">
          <el-input v-model="editedBlog.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="editedBlog.title"></el-input>
        </el-form-item>
                <el-form-item label="文章简介" prop="title">
          <el-input v-model="editedBlog.introduction"></el-input>
        </el-form-item>
        <el-form-item label="文章首图" prop="firstPicture">
          <el-input v-model="editedBlog.firstPicture"></el-input>
        </el-form-item>
        <el-form-item label="浏览次数" prop="views">
          <el-input v-model="editedBlog.views"></el-input>
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-select
            v-model="newBlogTypeId"
            :placeholder="editedBlog.type == null ? '' : editedBlog.type.name"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章标签">
          <el-select
            v-model="newBlogTagIds"
            multiple
            class="my-tag-multiChoose"
          >
            <el-option
              v-for="item in tagList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章正文">
          <div :id="id"></div>
        </el-form-item>
        <el-form-item label="提交修改">
          <el-button type="primary" @click="editBlog"
            >提交<i class="el-icon-upload el-icon--right"></i
          ></el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import $ from "jquery";
export default {
  data() {
    return {
      oldBlogData: {},
      editedBlog: {},
      editFormRules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        firstPicture: [
          { required: true, message: "请输入文章首图地址", trigger: "blur" },
        ],
        views: [
          { required: true, message: "浏览次数不能为空", trigger: "blur" },
        ],
        type: [{ required: true }],
        tag: [{ required: true }],
      },
      cateList: [],
      tagList: [],
      //新选择的文章类型
      newBlogTypeId: "",
      //新选择的文章标签
      newBlogTagIds: [],
      //编辑器
      //最终生成的编辑器
      editor: null,
      //默认选项
      defaultOptions: {
        width: "100%",
        height: 600,
        path: "/lib/editormd/lib/",
        theme: "dark",
        previewTheme: "dark",
        editorTheme: "pastel-on-dark",
        //markdown : md,   //动态设置的markdown文本
        codeFold: true,
        //syncScrolling : false,
        saveHTMLToTextarea: true, // 保存 HTML 到 Textarea
        searchReplace: true,
        //watch : false,                // 关闭实时预览
        htmlDecode: "style,script,iframe|on*", // 开启 HTML 标签解析，为了安全性，默认不开启
        //toolbar  : false,             //关闭工具栏
        //previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
        emoji: true,
        taskList: true,
        tocm: true, // Using [TOCM]
        tex: true, // 开启科学公式TeX语言支持，默认关闭
        flowChart: true, // 开启流程图支持，默认关闭
        sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
        //dialogLockScreen : false,   // 设置弹出层对话框不锁屏，全局通用，默认为true
        //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
        //dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为true
        //dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为0.1
        //dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
        //imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        //imageUploadURL: "./php/upload.php",
        onload: () => {
          //console.log("onload", this);
          this.editor.setMarkdown(this.editedBlog.content);
          //this.fullscreen();
          //this.unwatch();
          //this.watch().fullscreen();
          //this.width("100%");
          //this.height(480);
          //this.resize("100%", 640);
        },
      },
    };
  },
  props: {
    /**
     * editormd挂载元素的id
     */
    id: {
      type: String,
      default: "editor-md-div",
    },
    /**
     * editormd的选项对象
     */
    options: {
      type: Object,
    },
  },
  mounted() {
    this.getCateList();
    this.getTagList();
    this.getArticleById(this.$route.query.id);
  },
  methods: {
    async getArticleById(id) {
      const { data: res } = await this.$http.get("blog/" + id);
      this.oldBlogData = res.data;
      this.editedBlog = res.data;
      // 设置默认选中类型
      this.newBlogTypeId = this.editedBlog.typeId
      // 设置默认选中标签
      this.editedBlog.tags.map((v) => {
        this.newBlogTagIds.push(v.id);
      });
      let vm = this;
      // 设置编辑器
      this.requireEditor(function () {
        vm.editor = editormd(vm.id, vm.getOptions());
      });
    },
    // 获取所有分类
    async getCateList() {
      const { data: res } = await this.$http.get("type");
      this.cateList = res.data;
    },
    // 获取所有标签
    async getTagList() {
      const { data: res } = await this.$http.get("tag");
      this.tagList = res.data;
    },
    /**
     * 异步加载editormd
     * callback 成功后的回调函数
     */
    requireEditor(callback) {
      let vm = this;
      //设置全局变量，因为editormd依赖jquery
      window.$ = window.jQuery = $;
      //异步加载并执行
      $.getScript("/lib/editormd/editormd.min.js", function (script) {
        callback();
      });
      //加载css
      $("head").append(
        $('<link rel="stylesheet" type="text/css" />').attr(
          "href",
          "/lib/editormd/css/editormd.min.css"
        )
      );
    },
    /**
     * 得到最终的options，组件属性上获得的选项覆盖此处的默认选项
     */
    getOptions() {
      return Object.assign(this.defaultOptions, this.options);
    },
    async editBlog(){
      // 整理提交数据
      let editedBlogData = {}
      editedBlogData['title'] = this.editedBlog.title
      editedBlogData['introduction'] = this.editedBlog.introduction
      editedBlogData['content'] = this.editor.getMarkdown();
      editedBlogData['firstPicture'] = this.editedBlog.firstPicture
      editedBlogData['views'] = parseInt(this.editedBlog.views)
      editedBlogData['typeId'] = this.newBlogTypeId
      editedBlogData['tagIds'] = this.newBlogTagIds
      console.log(editedBlogData)
      try {
        const response = await this.$http.put("updateBlog/" + this.$route.query.id, editedBlogData);
        if (response.status === 200) {
          this.$message.success("修改文章成功！");
        }
      } catch (error) {
        console.log(error)
      }
    }
  },
};
</script>

<style lang="less" scoped>
.my-tag-multiChoose {
  width: 50%;
}
</style>